/**
 * MyExceptionHandler.java
 * com.ebook.core.exception
 * Copyright (c) 2013, 北京博观知翼有限公司版权所有.
*/

package com.ebook.core.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ebook.util.Status;
import com.google.gson.JsonParseException;

/**
 * springmvc异常处理类
 * @author   草帽
 * @Date	 2013-3-2 	 
 */
public class MyExceptionHandler implements HandlerExceptionResolver {
	
	private static Log logger = LogFactory.getLog(MyExceptionHandler.class); 

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String status = "success";
		String message = "";
		// 根据不同错误输出不同错误提示 
		if (ex instanceof DataAccessException) {
			logger.error("DataAccessException:"+ex.getMessage());
			status = Status.FAIL;
			message = "DataAccessException";
		} else if (ex instanceof JsonParseException) {
			logger.error("JsonParseException:"+ex.getMessage());
			status = Status.FAIL;
			message = "JsonParseException";
		} else if (ex instanceof IOException) {
			logger.error("IOException:"+ex.getMessage());
			status = Status.FAIL;
			message = "IOException";
		} else {
			logger.error("OtherException:"+ex.getMessage());
			status = Status.FAIL;
			message = "OtherException";
		}
		if(status.equals(Status.FAIL)){
			modelMap.put("message", message);
		}
		modelMap.put("status", status);
		return new ModelAndView().addAllObjects(modelMap);
	}
}